<template>
  <div class="student-resource-pool">
    <el-row :gutter="10" class="mb8">
      <el-col :span="6">
        <div class="view-switch">
          <el-radio-group v-model="currentView" @change="handleViewChange">
            <el-radio-button :label="'all'">全部学员</el-radio-button>
            <el-radio-button :label="'public'">公海学员</el-radio-button>
            <el-radio-button :label="'private'">我的私域</el-radio-button>
          </el-radio-group>
        </div>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Filter" @click="openFilter">筛选</el-button>
      </el-col>
      <el-col :span="1.5" v-if="currentUser.value && currentUser.value.role === 'admin'">
        <el-button type="primary" plain icon="Settings" @click="configDialog.open = true">公海配置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Refresh" @click="refreshList">刷新</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Plus" @click="addStudent">添加学员</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Export" @click="exportData">导出</el-button>
      </el-col>
      <el-col :span="6" :offset="11.5">
        <el-input v-model="searchQuery" placeholder="搜索学员..." prefix-icon="Search" @keyup.enter="handleSearch" />
      </el-col>
    </el-row>

    <el-card class="filter-card" v-if="filterVisible">
      <el-form :model="filterForm" inline label-width="80px">
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="全部">
            <el-option label="全部" value="" />
            <el-option label="陌生" value="陌生" />
            <el-option label="已联系" value="已联系" />
            <el-option label="意向" value="意向" />
            <el-option label="已报名" value="已报名" />
            <el-option label="已入职" value="已入职" />
            <el-option label="失效" value="失效" />
          </el-select>
        </el-form-item>
        <el-form-item label="来源渠道">
          <el-select v-model="filterForm.source" placeholder="全部">
            <el-option label="全部" value="" />
            <el-option label="官网" value="官网" />
            <el-option label="转介绍" value="转介绍" />
            <el-option label="线下活动" value="线下活动" />
            <el-option label="线上广告" value="线上广告" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程">
          <el-select v-model="filterForm.course" placeholder="全部">
            <el-option label="全部" value="" />
            <el-option label="前端开发" value="前端开发" />
            <el-option label="Java开发" value="Java开发" />
            <el-option label="UI设计" value="UI设计" />
            <el-option label="产品经理" value="产品经理" />
            <el-option label="数据分析" value="数据分析" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进人">
          <el-input v-model="filterForm.responsiblePerson" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-table :data="resourcePoolList" style="width: 100%" border v-loading="loading">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" label="学员ID" width="80" />
      <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="seaType" label="海域类型" width="100">
            <template #default="{ row }">
              <el-tag :type="row.seaType === SEA_TYPE.PUBLIC ? 'primary' : 'success'">
                {{ row.seaType === SEA_TYPE.PUBLIC ? '公海' : '私域' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="grabTime" label="领取时间" width="180" />
          <el-table-column prop="lockExpireTime" label="锁定截止" width="180" />
      <el-table-column prop="gender" label="性别" width="60" />
      <el-table-column prop="age" label="年龄" width="60" />
      <el-table-column prop="contact" label="联系方式" width="200" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="source" label="来源渠道" width="100" />
      <el-table-column prop="course" label="意向课程" width="100" />
      <el-table-column prop="tags" label="标签" width="150">
        <template #default="scope">
          <el-tag v-for="tag in scope.row.tags" :key="tag" size="small" style="margin-right: 5px;">{{ tag }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="responsiblePerson" label="跟进人" width="100" />
      <el-table-column prop="lastFollowTime" label="最后跟进时间" width="180" />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Eye" @click="viewDetails(scope.row)">查看</el-button>
          
          <!-- 公海学员操作 -->
          <template v-if="scope.row.seaType === SEA_TYPE.PUBLIC">
            <el-button link type="success" icon="Check" @click="grabStudent(scope.row)">领取</el-button>
          </template>
          
          <!-- 私域学员操作 -->
          <template v-else-if="scope.row.seaType === SEA_TYPE.PRIVATE">
            <template v-if="currentUser.value && (scope.row.responsiblePersonId === currentUser.value.id || currentUser.value.role === 'admin')">
              <el-button link type="warning" icon="Share" @click="transferDialog.student = scope.row; transferDialog.open = true">转移</el-button>
            </template>
            <template v-if="currentUser.value && currentUser.value.role === 'admin'">
              <el-button link type="danger" icon="ArrowRight" @click="releaseToPublic(scope.row)">释放</el-button>
            </template>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 学员详情对话框 -->
    <el-dialog :title="'学员详情 - ' + currentStudent.name" v-model="detailDialog.open" width="700px" append-to-body>
      <el-descriptions title="基本信息" :column="2">
        <el-descriptions-item label="姓名">{{ currentStudent.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ currentStudent.gender }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ currentStudent.age }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ currentStudent.contact }}</el-descriptions-item>
        <el-descriptions-item label="状态"><el-tag :type="getStatusType(currentStudent.status)">{{ currentStudent.status }}</el-tag></el-descriptions-item>
        <el-descriptions-item label="来源渠道">{{ currentStudent.source }}</el-descriptions-item>
        <el-descriptions-item label="意向课程">{{ currentStudent.course }}</el-descriptions-item>
        <el-descriptions-item label="期望岗位">{{ currentStudent.expectedPosition }}</el-descriptions-item>
        <el-descriptions-item label="学历">{{ currentStudent.education }}</el-descriptions-item>
        <el-descriptions-item label="工作经验">{{ currentStudent.workExperience }}</el-descriptions-item>
        <el-descriptions-item label="所在城市">{{ currentStudent.city }}</el-descriptions-item>
        <el-descriptions-item label="跟进人">{{ currentStudent.responsiblePerson }}</el-descriptions-item>
        <el-descriptions-item label="最后跟进时间">{{ currentStudent.lastFollowTime }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ currentStudent.remark }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="标签信息" :column="3" style="margin-top: 20px;">
        <el-descriptions-item v-for="tag in currentStudent.tags" :key="tag" :label="tag">{{ tag }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.open = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 公海配置对话框 -->
    <el-dialog title="公海配置" v-model="configDialog.open" width="600px" append-to-body>
      <el-form :model="publicSeaConfig" ref="configFormRef" label-width="150px">
        <el-form-item label="自动进入公海天数" prop="followUpTimeout">
          <el-input v-model="publicSeaConfig.followUpTimeout" type="number" placeholder="请输入天数" />
          <div class="el-form-item__help">学员超过该天数未跟进将自动进入公海</div>
        </el-form-item>
        <el-form-item label="领取后锁定小时数" prop="lockTime">
          <el-input v-model="publicSeaConfig.lockTime" type="number" placeholder="请输入小时数" />
          <div class="el-form-item__help">学员领取后锁定的时间，防止重复领取</div>
        </el-form-item>
        <el-form-item label="私域保护期(天)" prop="protectionPeriod">
          <el-input v-model="publicSeaConfig.protectionPeriod" type="number" placeholder="请输入天数" />
          <div class="el-form-item__help">私域学员的保护期，过期后可被他人领取</div>
        </el-form-item>
        <el-form-item label="分配规则" prop="allocationRule">
          <el-select v-model="publicSeaConfig.allocationRule" placeholder="请选择分配规则">
            <el-option :label="'抢单'" :value="ALLOCATION_RULE.GRAB" />
            <el-option :label="'轮转'" :value="ALLOCATION_RULE.ROTATE" />
            <el-option :label="'按权重'" :value="ALLOCATION_RULE.WEIGHT" />
          </el-select>
        </el-form-item>
        <el-form-item label="每天最大抢单数量" prop="maxGrabPerDay">
          <el-input v-model="publicSeaConfig.maxGrabPerDay" type="number" placeholder="请输入数量" />
          <div class="el-form-item__help">每个销售每天最多可抢单的数量</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="configDialog.open = false">取 消</el-button>
          <el-button type="primary" @click="savePublicSeaConfig">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 转移学员对话框 -->
    <el-dialog title="转移学员" v-model="transferDialog.open" width="500px" append-to-body>
      <el-form :model="transferDialog" ref="transferFormRef" label-width="100px">
        <el-form-item label="学员名称" prop="student.name">
          <el-input v-model="transferDialog.student.name" disabled />
        </el-form-item>
        <el-form-item label="当前负责人" prop="student.responsiblePerson">
          <el-input v-model="transferDialog.student.responsiblePerson" disabled />
        </el-form-item>
        <el-form-item label="目标负责人" prop="targetUser" required>
          <el-select v-model="transferDialog.targetUser" placeholder="请选择目标负责人">
            <el-option v-for="user in availableUsers" :key="user.id" :label="user.name" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="转移原因" prop="reason">
          <el-input v-model="transferDialog.reason" type="textarea" placeholder="请输入转移原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="transferDialog.open = false">取 消</el-button>
          <el-button type="primary" @click="handleTransfer">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加/编辑学员对话框 -->
    <el-dialog :title="studentForm.id ? '编辑学员' : '添加学员'" v-model="studentDialog.open" width="600px" append-to-body>
      <el-form :model="studentForm" ref="studentFormRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="studentForm.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="studentForm.age" type="number" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="studentForm.contact" placeholder="请输入电话/邮箱" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="studentForm.status" placeholder="请选择状态">
            <el-option label="陌生" value="陌生" />
            <el-option label="已联系" value="已联系" />
            <el-option label="意向" value="意向" />
            <el-option label="已报名" value="已报名" />
            <el-option label="已入职" value="已入职" />
            <el-option label="失效" value="失效" />
          </el-select>
        </el-form-item>
        <el-form-item label="来源渠道" prop="source">
          <el-select v-model="studentForm.source" placeholder="请选择来源渠道">
            <el-option label="官网" value="官网" />
            <el-option label="转介绍" value="转介绍" />
            <el-option label="线下活动" value="线下活动" />
            <el-option label="线上广告" value="线上广告" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="意向课程" prop="course">
          <el-select v-model="studentForm.course" placeholder="请选择意向课程">
            <el-option label="前端开发" value="前端开发" />
            <el-option label="Java开发" value="Java开发" />
            <el-option label="UI设计" value="UI设计" />
            <el-option label="产品经理" value="产品经理" />
            <el-option label="数据分析" value="数据分析" />
          </el-select>
        </el-form-item>
        <el-form-item label="期望岗位" prop="expectedPosition">
          <el-input v-model="studentForm.expectedPosition" placeholder="请输入期望岗位" />
        </el-form-item>
        <el-form-item label="学历" prop="education">
          <el-input v-model="studentForm.education" placeholder="请输入学历" />
        </el-form-item>
        <el-form-item label="工作经验" prop="workExperience">
          <el-input v-model="studentForm.workExperience" placeholder="请输入工作经验" />
        </el-form-item>
        <el-form-item label="所在城市" prop="city">
          <el-input v-model="studentForm.city" placeholder="请输入所在城市" />
        </el-form-item>
        <el-form-item label="跟进人" prop="responsiblePerson">
          <el-input v-model="studentForm.responsiblePerson" placeholder="请输入跟进人" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="studentForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="标签">
          <el-tag v-for="tag in studentForm.tags" :key="tag" closable @close="removeStudentTag(tag)">{{ tag }}</el-tag>
          <el-input v-model="newTag" placeholder="输入标签后按回车添加" style="width: auto; display: inline-block; margin-left: 10px;" @keyup.enter="addStudentTag" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitStudentForm">确 定</el-button>
          <el-button @click="studentDialog.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 海域类型枚举
const SEA_TYPE = {
  PUBLIC: 'public', // 公海
  PRIVATE: 'private' // 私域
}

// 分配规则枚举
const ALLOCATION_RULE = {
  GRAB: 'grab', // 抢单
  ROTATE: 'rotate', // 轮转
  WEIGHT: 'weight' // 按权重
}

// 公海配置
const publicSeaConfig = reactive({
  followUpTimeout: 30, // 多少天未跟进自动进入公海
  lockTime: 24, // 领取后锁定多少小时
  protectionPeriod: 90, // 私域保护期（天）
  allocationRule: ALLOCATION_RULE.GRAB, // 默认分配规则
  maxGrabPerDay: 5, // 每天最大抢单数量
})

// 当前登录用户信息
const currentUser = ref({
  id: 'user123',
  name: '当前用户',
  department: '销售部',
  role: 'sales'
})

// 今日抢单数量
const todayGrabCount = ref(0)

// 原始资源池列表数据
const rawResourcePoolList = ref([])

// 资源池列表数据（根据当前视图过滤）
const resourcePoolList = computed(() => {
  if (currentView.value === 'public') {
    return publicSeaList.value
  } else if (currentView.value === 'private') {
    return privateSeaList.value
  } else {
    return rawResourcePoolList.value
  }
})

// 处理视图切换
function handleViewChange() {
  // 根据当前视图重新加载数据
  getResourcePoolList()
}

// 加载状态
const loading = ref(false)

// 公海学员列表
const publicSeaList = computed(() => {
  return resourcePoolList.value.filter(student => student.seaType === SEA_TYPE.PUBLIC)
})

// 私域学员列表
const privateSeaList = computed(() => {
  return resourcePoolList.value.filter(student => 
    student.seaType === SEA_TYPE.PRIVATE && 
    currentUser.value && student.responsiblePersonId === currentUser.value.id
  )
})

// 当前视图：all, public, private
const currentView = ref('all')

// 领取公海学员对话框
const grabDialog = reactive({
  open: false,
  student: null
})

// 转移学员对话框
const transferDialog = reactive({
  open: false,
  student: null,
  targetUser: ''
})

// 审批记录
const approvalRecords = ref([])

// 公海配置对话框
const configDialog = reactive({
  open: false
})

// 保存公海配置
function savePublicSeaConfig() {
  // 这里应该调用API保存配置
  ElMessage.success('公海配置已保存')
  configDialog.open = false
}

// 检查并释放超时未跟进的学员
function checkAndReleaseExpired() {
  const now = new Date()
  resourcePoolList.value.forEach(student => {
    // 检查是否超过跟进时间且在私域中
    if (student.seaType === SEA_TYPE.PRIVATE && student.lastFollowTime) {
      const lastFollowDate = new Date(student.lastFollowTime)
      const diffDays = Math.floor((now - lastFollowDate) / (1000 * 60 * 60 * 24))
      
      if (diffDays >= publicSeaConfig.followUpTimeout) {
        // 自动释放到公海
        student.seaType = SEA_TYPE.PUBLIC
        student.responsiblePerson = ''
        student.responsiblePersonId = ''
        student.releaseTime = now.toISOString().replace('T', ' ').substr(0, 19)
        student.releaseReason = '长期未跟进'
        
        ElMessage.info(`学员 ${student.name} 因长期未跟进已释放到公海`)
      }
    }
  })
}

// 领取公海学员
function grabStudent(student) {
  // 检查是否已达到今日抢单上限
  if (todayGrabCount.value >= publicSeaConfig.maxGrabPerDay) {
    ElMessage.warning(`今日已达到抢单上限 ${publicSeaConfig.maxGrabPerDay} 个`)
    return
  }
  
  // 检查是否有权限领取
  if (currentUser.value && (currentUser.value.role !== 'admin' && currentUser.value.role !== 'sales')) {
    ElMessage.warning('没有权限领取学员')
    return
  }
  
  // 模拟并发抢单处理
  const isGrabbed = Math.random() > 0.1 // 90%成功率
  
  if (isGrabbed) {
    student.seaType = SEA_TYPE.PRIVATE
    student.responsiblePerson = currentUser.value.name
    student.responsiblePersonId = currentUser.value.id
    student.grabTime = new Date().toISOString().replace('T', ' ').substr(0, 19)
    student.lockExpireTime = new Date(Date.now() + publicSeaConfig.lockTime * 60 * 60 * 1000)
      .toISOString().replace('T', ' ').substr(0, 19)
    
    todayGrabCount.value++
    ElMessage.success(`成功领取学员 ${student.name}`)
  } else {
    ElMessage.error(`学员 ${student.name} 已被其他销售领取`)
  }
}

// 释放学员到公海
function releaseToPublic(student) {
  ElMessageBox.confirm('确定要将此学员释放到公海吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    student.seaType = SEA_TYPE.PUBLIC
    student.responsiblePerson = ''
    student.responsiblePersonId = ''
    student.releaseTime = new Date().toISOString().replace('T', ' ').substr(0, 19)
    student.releaseReason = '管理员手动释放'
    
    ElMessage.success('已成功释放学员到公海')
  }).catch(() => {
    // 取消操作
  })
}

// 可转移的目标用户列表
const availableUsers = ref([
  { id: 'user1', name: '张三' },
  { id: 'user2', name: '李四' },
  { id: 'user3', name: '王五' },
  { id: 'user4', name: '赵六' }
])

// 处理学员转移
function handleTransfer() {
  if (!transferDialog.targetUser) {
    ElMessage.warning('请选择目标负责人')
    return
  }
  
  const targetUser = availableUsers.value.find(u => u.id === transferDialog.targetUser)
  if (!targetUser) {
    ElMessage.warning('选择的目标负责人不存在')
    return
  }
  
  transferStudent(transferDialog.student, targetUser.id, targetUser.name)
  transferDialog.open = false
}

// 转移学员
function transferStudent(student, targetUserId, targetUserName) {
  // 检查是否有权限转移
  if (currentUser.value && (student.responsiblePersonId !== currentUser.value.id && currentUser.value.role !== 'admin')) {
    ElMessage.warning('没有权限转移此学员')
    return
  }
  
  // 记录审批
  const approval = {
    id: Date.now(),
    studentId: student.id,
    studentName: student.name,
    fromUserId: currentUser.value ? currentUser.value.id : '',
    fromUserName: currentUser.value ? currentUser.value.name : '',
    toUserId: targetUserId,
    toUserName: targetUserName,
    reason: '手动转移',
    status: 'pending',
    createTime: new Date().toISOString().replace('T', ' ').substr(0, 19)
  }
  
  approvalRecords.value.push(approval)
  
  // 管理员可以直接转移，无需审批
  if (currentUser.value && currentUser.value.role === 'admin') {
    student.seaType = SEA_TYPE.PRIVATE
    student.responsiblePerson = targetUserName
    student.responsiblePersonId = targetUserId
    approval.status = 'approved'
    approval.approveTime = new Date().toISOString().replace('T', ' ').substr(0, 19)
    ElMessage.success(`已成功转移学员 ${student.name} 给 ${targetUserName}`)
  } else {
    ElMessage.info(`已提交学员 ${student.name} 的转移申请，等待审批`)
  }
}

// 搜索查询
const searchQuery = ref('')

// 筛选表单
const filterForm = reactive({
  status: '',
  source: '',
  course: '',
  responsiblePerson: ''
})

// 筛选可见性
const filterVisible = ref(false)

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 详情对话框
const detailDialog = reactive({
  open: false
})

// 当前学员
const currentStudent = ref({})

// 学员对话框
const studentDialog = reactive({
  open: false
})

// 学员表单
const studentForm = reactive({
  id: '',
  name: '',
  gender: '',
  age: '',
  contact: '',
  status: '陌生',
  source: '',
  course: '',
  expectedPosition: '',
  education: '',
  workExperience: '',
  city: '',
  tags: [],
  responsiblePerson: '',
  remark: ''
})

// 新标签
const newTag = ref('')

// 状态样式映射
const statusMap = {
  '陌生': 'info',
  '已联系': 'success',
  '意向': 'warning',
  '已报名': 'primary',
  '已入职': 'success',
  '失效': 'danger'
}

// 获取状态对应的标签类型
const getStatusType = (status) => {
  return statusMap[status] || ''
}

// 打开筛选
const openFilter = () => {
  filterVisible.value = !filterVisible.value
}

// 刷新列表
const refreshList = () => {
  getResourcePoolList()
}

// 处理搜索
const handleSearch = () => {
  getResourcePoolList()
}

// 处理筛选
const handleFilter = () => {
  getResourcePoolList()
}

// 重置筛选
const resetFilter = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  getResourcePoolList()
}

// 查看详情
const viewDetails = (row) => {
  currentStudent.value = { ...row }
  detailDialog.open = true
}

// 添加学员
const addStudent = () => {
  studentForm.id = ''
  studentForm.name = ''
  studentForm.gender = ''
  studentForm.age = ''
  studentForm.contact = ''
  studentForm.status = '陌生'
  studentForm.source = ''
  studentForm.course = ''
  studentForm.expectedPosition = ''
  studentForm.education = ''
  studentForm.workExperience = ''
  studentForm.city = ''
  studentForm.tags = []
  studentForm.responsiblePerson = ''
  studentForm.remark = ''
  newTag.value = ''
  studentDialog.open = true
}

// 编辑学员
const editStudent = (row) => {
  studentForm.id = row.id
  studentForm.name = row.name
  studentForm.gender = row.gender
  studentForm.age = row.age
  studentForm.contact = row.contact
  studentForm.status = row.status
  studentForm.source = row.source
  studentForm.course = row.course
  studentForm.expectedPosition = row.expectedPosition
  studentForm.education = row.education
  studentForm.workExperience = row.workExperience
  studentForm.city = row.city
  studentForm.tags = [...row.tags]
  studentForm.responsiblePerson = row.responsiblePerson
  studentForm.remark = row.remark
  newTag.value = ''
  studentDialog.open = true
}

// 删除学员
const deleteStudent = (row) => {
  ElMessageBox.confirm('确定要删除该学员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除操作
    const index = resourcePoolList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      resourcePoolList.value.splice(index, 1)
      pagination.total--
    }
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消操作
  })
}

// 添加学员标签
const addStudentTag = () => {
  if (newTag.value && !studentForm.tags.includes(newTag.value)) {
    studentForm.tags.push(newTag.value)
    newTag.value = ''
  }
}

// 移除学员标签
const removeStudentTag = (tag) => {
  studentForm.tags = studentForm.tags.filter(item => item !== tag)
}

// 提交学员表单
const submitStudentForm = () => {
  // 模拟表单提交
  if (studentForm.id) {
    // 编辑
    const index = resourcePoolList.value.findIndex(item => item.id === studentForm.id)
    if (index !== -1) {
      resourcePoolList.value[index] = { ...studentForm }
    }
    ElMessage.success('编辑成功')
  } else {
    // 添加
    studentForm.id = Date.now()
    studentForm.lastFollowTime = new Date().toISOString().replace('T', ' ').substr(0, 19)
    resourcePoolList.value.unshift({ ...studentForm })
    pagination.total++
    ElMessage.success('添加成功')
  }
  studentDialog.open = false
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  getResourcePoolList()
}

// 当前页码变化
const handleCurrentChange = (current) => {
  pagination.currentPage = current
  getResourcePoolList()
}

// 获取资源池列表
function getResourcePoolList() {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    const mockData = []
    for (let i = 1; i <= 20; i++) {
      // 随机海域类型：70%公海，30%私域
      const seaType = Math.random() > 0.3 ? SEA_TYPE.PUBLIC : SEA_TYPE.PRIVATE
      const responsiblePersonId = seaType === SEA_TYPE.PRIVATE ? ['user1', 'user2', 'user3', 'user4'][Math.floor(Math.random() * 4)] : ''
      const responsiblePerson = responsiblePersonId ? availableUsers.value.find(u => u.id === responsiblePersonId)?.name : ''
      const grabTime = seaType === SEA_TYPE.PRIVATE ? new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString().replace('T', ' ').substr(0, 19) : ''
      const lockExpireTime = seaType === SEA_TYPE.PRIVATE ? new Date(Date.now() + publicSeaConfig.lockTime * 60 * 60 * 1000).toISOString().replace('T', ' ').substr(0, 19) : ''
      const lastFollowTime = new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString().replace('T', ' ').substr(0, 19)
      
      mockData.push({
        id: 'STU' + i.toString().padStart(4, '0'),
        name: '学员' + i,
        gender: i % 2 === 0 ? '女' : '男',
        age: 18 + Math.floor(Math.random() * 10),
        contact: '1380013800' + i % 10,
        status: ['陌生', '已联系', '意向', '已报名', '已入职', '失效'][Math.floor(Math.random() * 6)],
        source: ['官网', '转介绍', '线下活动', '线上广告', '其他'][Math.floor(Math.random() * 5)],
        course: ['前端开发', 'Java开发', 'UI设计', '产品经理', '数据分析'][Math.floor(Math.random() * 5)],
        tags: ['标签' + Math.floor(Math.random() * 10), '标签' + Math.floor(Math.random() * 10)],
        responsiblePerson,
        responsiblePersonId,
        lastFollowTime,
        seaType,
        grabTime,
        lockExpireTime,
        expectedPosition: 'Web前端开发',
        education: '本科',
        workExperience: '1-3年',
        city: '北京',
        remark: '这是学员备注信息'
      })
    }
    rawResourcePoolList.value = mockData
    pagination.total = 100
    loading.value = false
  }, 500)
}

// 页面加载时执行
onMounted(() => {
  getResourcePoolList()
  // 每隔一段时间检查并释放超时未跟进的学员
  setInterval(checkAndReleaseExpired, 3600000) // 每小时检查一次
})
</script>

<style scoped>
.student-resource-pool {
  padding: 20px;
}

.filter-card {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>